package com.vast.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vast.admin.annotation.PassToken;
import com.vast.admin.entity.Company;
import com.vast.admin.service.impl.CompanyService;
import com.vast.common.constant.Constants;
import com.vast.common.constant.MessageCode;
import com.vast.common.core.domain.AjaxResult;
import com.vast.common.core.domain.Result;
import com.vast.common.core.domain.entity.SysMenu;
import com.vast.common.core.domain.entity.SysUser;
import com.vast.common.core.domain.model.LoginBody;
import com.vast.common.core.domain.model.LoginUser;
import com.vast.common.utils.ServletUtils;
import com.vast.framework.web.service.SysLoginService;
import com.vast.framework.web.service.SysPermissionService;
import com.vast.framework.web.service.TokenService;
import com.vast.system.domain.SysUserRole;
import com.vast.system.service.ISysMenuService;
import com.vast.system.service.ISysUserRoleService;
import com.vast.system.utils.Constant;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private ISysUserRoleService managerRoleService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


		// 登录
	@ApiOperation(value = "用户登录接口", notes = "根据用户名,密码登录")
	@PostMapping("/loginAdmin")
	@PassToken
	public Result<SysUser> loginAdmin(@RequestBody LoginBody loginBody) {
		// 生成令牌
		String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());
		SysUser manager = tokenService.getLoginUser(token).getUser();
		manager.setToken(token);
		List<SysUserRole> managerRoles = managerRoleService.list(new QueryWrapper<SysUserRole>().eq(SysUserRole.COL_MANAGER_ID,manager.getUserId()));
		List<Long> roleIds = new ArrayList<>();
		for (SysUserRole managerRole : managerRoles) {
			roleIds.add(managerRole.getRoleId());
		}
		Long[] roleIdArr = new Long[roleIds.size()];
		roleIds.toArray(roleIdArr);
		manager.setRoleIdList(roleIdArr);
		if(!Arrays.asList(manager.getRoleIdList()).contains(Constant.SUPER_ADMIN)){//超级管理员
			if(manager.getCompanyId() != null && manager.getCompanyId() > 0){
				Company company = companyService.getById(manager.getCompanyId());
				if(company != null){
					manager.setCompanyName(company.getName());
				}
			}

		}else{
			manager.setCompanyName("系统管理");
		}

		return new Result<SysUser>(MessageCode.SUCCESS, "登录成功",manager);
	}



    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
